
import pinia from '@/store/store'
import { RouteRecordRaw, createRouter, createWebHistory,useRouter } from 'vue-router'
import Layout from '@/layout/index.vue'
import { useRoutesStore } from '@/store/routes'

const routesStore = useRoutesStore(pinia)
const routers = useRouter()

// 公共路由
export const constantRoutes =[
    {
        path: '',
        redirect: '/index',
        //使用import可以路由懒加载，如果不使用，太多组件一起加载会造成白屏
        component: Layout,
        children:[
            {
                path: '/index',
                component: () => import('@/views/index.vue'),
                name: 'Index',
                meta: { title: '首页', icon: 'dashboard', affix: true }
            }
        ]
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login.vue')
    }
    //{
        //配置404页面
        //path: '/:catchAll(.*)',
        //name: '404',
        //component: () => import(''),
    //}
]

// 路由
const router = createRouter({
    history: createWebHistory(),
    routes:constantRoutes
})
router.beforeEach(async(to,from,next) =>{
    //第一个参数to，包含的内容是切换后的路由对象，也就是跳转后的路由对象
    //第二个参数from，包含的内容的是切换前的路由对象，也就是跳转前的路由对象
    //第三个参数next()，是否往下执行，执行的话，如果不写的话路由就不会跳转，操作将会终止
    if(!routesStore.routes.length){
        let menus = JSON.parse(localStorage.getItem('menus'))
        if(menus?.length){
            await routesStore.addRoutes(menus,router)
            router.getRoutes()
            console.log(routesStore.routes,'1111111111111',router.getRoutes())
            next({ ...to, replace: true })
        }else{
            next()
        }
    }else{
        router.getRoutes()
        next()
    }
  })
// 导出
export default router
